import Vue from 'vue'
import Vuex from 'vuex'
import http from '../js_sdk/luch-request/luch-request/index'

Vue.use(Vuex)

import localStorage from '../localStorage'
import config from '@/config'

const store = new Vuex.Store({
	state: {
		scene: 0,				// 场景值
		hasLogin: false,		// 是否已经登录
		userinfo: {},			// 登录用户信息
		businessList: [],		// 绑定的商户
	},
	getters: {
		// 默认商户
		defaultBusiness(state) {
			let arr = state.businessList.filter(a => a.id === state.userinfo.defaultBusiness)
			if (arr.length > 0) return arr[0]
			return undefined
		}
	},
	mutations: {
		// login(state, provider) {

		// 	state.hasLogin = true;
		// 	state.userInfo = provider;
		// 	uni.setStorage({//缓存用户登陆状态
		// 	    key: 'userInfo',  
		// 	    data: provider  
		// 	}) 
		// 	console.log(state.userInfo);
		// }
		// 设置场景值
		setScene(state, scene) {
			state.scene = scene
		},
		// 设置用户信息
		setUserInfo(state, info) {
			state.userinfo = info
			localStorage.setUserinfo(info)
		},
		// 设置是否登录授权
		setIsLogin(state, hasLogin) {
			state.hasLogin = !!hasLogin
		},
		// 设置用户绑定的商户
		setBusinessList(state, businesses) {
			state.businessList = businesses
		},
		// 新增绑定的商户
		addBusiness(state, business) {
			state.businessList.push(business)
		},
		// 移除门店
		removeBusiness(state, id) {
			state.businessList.remove(item => item.id === id)
		}
	},
	actions: {
		// 获取根据code获取用户openid，读取用户
		async login({ commit, state }) {
			let userinfo = localStorage.getUserinfo()
			if (!userinfo) {
				let task = new Promise(function(resolve, reject) {
					uni.login({
						provider: 'weixin',
						async success(info) {
							let [, res] = await uni.request({ url: `${config.baseURL}/token/code/${info.code}`, method: 'GET' })
							localStorage.setUserinfo(res.data.data)
							resolve(res.data.data)
						}
					})
				})
				userinfo = await task
			}
			commit('setUserInfo', userinfo)
			commit('setIsLogin', userinfo.isRegister)
			
		},
		async appInit({ commit }){
			let { data } = await http.get('/wxuser/init')
			commit('setBusinessList', data.data.businesses)
		}
	}
})

export default store
